package cn.edu.cqvie.ssm.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
 
import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSourceFactory;

import cn.edu.cqvie.ssm.entity.Student;
 
 
//使用DBCP数据源
public class DBCPUtil {
	
	//1.定义一个数据源
	private static DataSource ds;
	
	//2.给数据源赋值
	static {
		Properties prop = new Properties();
		try {
			prop.load(DBCPUtil.class.getClassLoader().getResourceAsStream("dbcp.properties"));
			ds = BasicDataSourceFactory.createDataSource(prop);//得到数据源
		} catch (Exception e) {
			e.printStackTrace();
			throw new ExceptionInInitializerError("初始化数据源错误");
		}
	}
	
	//3.获取数据源
	public static DataSource getDataSource() {
		return ds;
	}
	
	//4.获取连接
	public static Connection getConnection() {
		try {
			return ds.getConnection();
		} catch (SQLException e) {
			throw new RuntimeException("获取连接失败");
		}
	}
	
	// 测试
	public static void main(String[] args) {
		
		Student stu = Student.builder()
				.id(101)
				.name("Mack")
				.sex("男")
				.age(40)
				.score(100)
				.grade("无")
				.photo("").build();
		Connection con = null;
		PreparedStatement ps = null;
		try {
			con = DBCPUtil.getConnection();
			String sql = "insert into student values(?,?,?,?,?,?,?)";
			ps = con.prepareStatement(sql);

			ps.setInt(1, stu.getId());
			ps.setString(2, stu.getName());
			ps.setString(3, stu.getSex());
			ps.setInt(4, stu.getAge());
			ps.setString(5, stu.getGrade());
			ps.setInt(6, stu.getScore());
			ps.setString(7, stu.getPhoto());

			ps.executeUpdate();
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {
			//不需要关闭
//			Dbconn.close(con, ps, null);
		}
	}
}